<template>
  <!-- 无障碍提示组件 -->
  <div 
    class="accessibility-alert"
    :class="{
      'visible': visible,
      'type-' + type,
      'position-' + position,
      'high-contrast': $accessibility?.service?.isHighContrastEnabled()
    }"
    v-aria="{
      live: 'assertive',
      atomic: true,
      role: 'alert'
    }"
    ref="alertRef"
  >
    <div class="alert-content">
      <icon :name="iconName" v-if="iconName" class="alert-icon" />
      <div class="alert-text">{{ message }}</div>
      <button 
        class="close-button" 
        v-if="showClose" 
        @click="close"
        aria-label="关闭提示"
        v-keyboard="{ escape: close }"
      >
        <icon name="close" />
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, inject } from 'vue';
import Icon from '../common/Icon.vue';

// 定义组件属性
const props = defineProps({
  // 提示消息
  message: {
    type: String,
    required: true
  },
  
  // 提示类型: info, success, warning, error, announcement
  type: {
    type: String,
    default: 'info',
    validator: (value) => ['info', 'success', 'warning', 'error', 'announcement'].includes(value)
  },
  
  // 显示时间（毫秒），0表示不自动关闭
  duration: {
    type: Number,
    default: 3000
  },
  
  // 是否显示关闭按钮
  showClose: {
    type: Boolean,
    default: true
  },
  
  // 位置: top, bottom, top-left, top-right, bottom-left, bottom-right, center
  position: {
    type: String,
    default: 'top',
    validator: (value) => ['top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right', 'center'].includes(value)
  },
  
  // 是否自动朗读
  autoAnnounce: {
    type: Boolean,
    default: true
  },
  
  // 朗读优先级
  priority: {
    type: String,
    default: 'normal',
    validator: (value) => ['high', 'normal', 'low'].includes(value)
  },
  
  // 是否启用震动反馈（移动设备）
  vibrate: {
    type: Boolean,
    default: false
  },
  
  // 震动模式（毫秒数组）
  vibratePattern: {
    type: Array,
    default: () => [100, 50, 100]
  }
});

// 定义组件事件
const emit = defineEmits(['show', 'hide', 'close', 'announced']);

// 注入无障碍服务
const accessibilityService = inject('accessibilityService');

// 响应式数据
const visible = ref(false);
const alertRef = ref(null);
let timer = null;
let animationFrame = null;

// 计算属性 - 图标名称
const iconName = computed(() => {
  const iconMap = {
    info: 'info-circle',
    success: 'check-circle',
    warning: 'exclamation-triangle',
    error: 'exclamation-circle',
    announcement: 'volume-up'
  };
  return iconMap[props.type];
});

// 显示提示
const show = () => {
  visible.value = true;
  
  // 触发显示事件
  emit('show');
  
  // 等待DOM更新后处理
  nextTick(() => {
    if (alertRef.value) {
      // 设置焦点（如果配置启用）
      if (accessibilityService?.getConfig()?.focusOnAlert) {
        try {
          alertRef.value.focus();
        } catch (e) {
          console.warn('无法设置提示焦点:', e);
        }
      }
      
      // 应用震动反馈
      if (props.vibrate && navigator.vibrate) {
        navigator.vibrate(props.vibratePattern);
      }
    }
  });
  
  // 处理自动朗读
  if (props.autoAnnounce && accessibilityService) {
    const config = accessibilityService.getConfig();
    
    if (config?.screenReaderEnabled || config?.autoAnnounce) {
      // 调用无障碍服务的朗读功能
      accessibilityService.announce(props.message, {
        priority: props.priority,
        type: props.type
      }).then(() => {
        // 触发朗读完成事件
        emit('announced');
      }).catch((error) => {
        console.warn('朗读失败:', error);
      });
    }
  }
  
  // 设置自动关闭定时器
  if (props.duration > 0) {
    timer = setTimeout(() => {
      close();
    }, props.duration);
  }
};

// 关闭提示
const close = () => {
  // 清除定时器
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  
  // 隐藏提示
  visible.value = false;
  
  // 触发隐藏和关闭事件
  emit('hide');
  emit('close');
  
  // 使用动画帧确保视觉效果
  animationFrame = requestAnimationFrame(() => {
    // 可以在这里添加额外的清理逻辑
  });
};

// 重新显示提示
const reshow = () => {
  // 先关闭，再显示
  close();
  
  animationFrame = requestAnimationFrame(() => {
    setTimeout(() => {
      show();
    }, 300); // 等待动画完成
  });
};

// 更新消息
const updateMessage = (newMessage) => {
  // 更新属性值
  props.message = newMessage;
  
  // 如果已经显示，则重新显示
  if (visible.value) {
    reshow();
  }
};

// 生命周期钩子
onMounted(() => {
  // 自动显示
  show();
  
  // 添加键盘事件监听
  const handleKeydown = (event) => {
    if (event.key === 'Escape' && visible.value) {
      event.preventDefault();
      close();
    }
  };
  
  document.addEventListener('keydown', handleKeydown);
  
  // 存储清理函数
  onUnmounted(() => {
    // 清除定时器和动画帧
    if (timer) {
      clearTimeout(timer);
    }
    
    if (animationFrame) {
      cancelAnimationFrame(animationFrame);
    }
    
    // 移除事件监听
    document.removeEventListener('keydown', handleKeydown);
  });
});

// 导出公共方法
defineExpose({
  show,
  close,
  reshow,
  updateMessage,
  isVisible: () => visible.value
});
</script>

<style scoped>
.accessibility-alert {
  position: fixed;
  z-index: var(--z-alert, 9999);
  max-width: 90%;
  margin: 0 auto;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: var(--color-background, #ffffff);
  color: var(--color-text, #333333);
  transition: opacity 0.3s ease, transform 0.3s ease;
  opacity: 0;
  transform: translateY(-20px);
  pointer-events: all;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 位置样式 */
.accessibility-alert.position-top {
  top: 20px;
  left: 50%;
  transform: translateX(-50%) translateY(-20px);
}

.accessibility-alert.position-bottom {
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%) translateY(20px);
}

.accessibility-alert.position-top-left {
  top: 20px;
  left: 20px;
  transform: translateY(-20px);
}

.accessibility-alert.position-top-right {
  top: 20px;
  right: 20px;
  transform: translateY(-20px);
}

.accessibility-alert.position-bottom-left {
  bottom: 20px;
  left: 20px;
  transform: translateY(20px);
}

.accessibility-alert.position-bottom-right {
  bottom: 20px;
  right: 20px;
  transform: translateY(20px);
}

.accessibility-alert.position-center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0.9);
}

/* 显示状态 */
.accessibility-alert.visible {
  opacity: 1;
  transform: translateX(-50%) translateY(0);
}

.accessibility-alert.visible.position-top-left,
.accessibility-alert.visible.position-top-right {
  transform: translateY(0);
}

.accessibility-alert.visible.position-bottom-left,
.accessibility-alert.visible.position-bottom-right {
  transform: translateY(0);
}

.accessibility-alert.visible.position-center {
  transform: translate(-50%, -50%) scale(1);
}

/* 类型样式 */
.accessibility-alert.type-info {
  background-color: var(--color-info, #e3f2fd);
  color: var(--color-info-text, #0d47a1);
  border-left: 4px solid var(--color-info-border, #1976d2);
}

.accessibility-alert.type-success {
  background-color: var(--color-success, #e8f5e9);
  color: var(--color-success-text, #2e7d32);
  border-left: 4px solid var(--color-success-border, #4caf50);
}

.accessibility-alert.type-warning {
  background-color: var(--color-warning, #fff8e1);
  color: var(--color-warning-text, #ff8f00);
  border-left: 4px solid var(--color-warning-border, #ffc107);
}

.accessibility-alert.type-error {
  background-color: var(--color-error, #ffebee);
  color: var(--color-error-text, #c62828);
  border-left: 4px solid var(--color-error-border, #f44336);
}

.accessibility-alert.type-announcement {
  background-color: var(--color-announcement, #f3e5f5);
  color: var(--color-announcement-text, #5e35b1);
  border-left: 4px solid var(--color-announcement-border, #9c27b0);
}

/* 内容样式 */
.alert-content {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 12px;
}

.alert-icon {
  flex-shrink: 0;
  font-size: 24px;
}

.alert-text {
  flex: 1;
  font-size: 16px;
  line-height: 1.5;
  margin: 0;
  padding: 0;
}

/* 关闭按钮 */
.close-button {
  flex-shrink: 0;
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  margin: -4px;
  border-radius: 4px;
  color: inherit;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
}

.close-button:hover,
.close-button:focus {
  background-color: rgba(0, 0, 0, 0.1);
  outline: 2px solid var(--color-focus, #1976d2);
  outline-offset: 2px;
}

.close-button:focus {
  outline: 2px solid var(--color-focus, #1976d2);
  outline-offset: 2px;
}

.close-button svg {
  width: 20px;
  height: 20px;
}

/* 高对比度模式 */
.accessibility-alert.high-contrast {
  border: 2px solid currentColor;
  box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.2);
}

.accessibility-alert.high-contrast.close-button {
  border: 1px solid currentColor;
}

/* 减少动画模式 */
@media (prefers-reduced-motion: reduce) {
  .accessibility-alert {
    transition: none;
    opacity: 1 !important;
    transform: translateX(-50%) translateY(0) !important;
  }
  
  .accessibility-alert.position-center {
    transform: translate(-50%, -50%) scale(1) !important;
  }
}

/* 键盘焦点样式 */
.accessibility-alert:focus {
  outline: 2px solid var(--color-focus, #1976d2);
  outline-offset: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .accessibility-alert {
    width: calc(100% - 40px);
    max-width: calc(100% - 40px);
    margin: 0 20px;
    padding: 12px;
  }
  
  .accessibility-alert.position-top,
  .accessibility-alert.position-bottom {
    left: 20px;
    right: 20px;
    transform: translateY(-20px);
  }
  
  .accessibility-alert.visible.position-top,
  .accessibility-alert.visible.position-bottom {
    transform: translateY(0);
  }
  
  .alert-text {
    font-size: 14px;
  }
}
</style>